//
//  WaveView.m
//  PhnixHome
//
//  Created by Levy Xu on 2018/3/10.
//  Copyright © 2018年 Levy Xu. All rights reserved.
//

#import "WaveView.h"

@interface WaveView ()
@property (nonatomic, strong) CAShapeLayer *shapeLayer;
@property (nonatomic, strong) CADisplayLink *displayLink;
@end

@implementation WaveView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self commitInit];
        [self addShapeLayer];
        [self startDisplayLink];
    }
    return self;
}

-(void)setWaveColor:(UIColor *)waveColor {
    _waveColor = waveColor;
    
    [self stopDisplayLink];
    [self.shapeLayer removeFromSuperlayer];
    
    [self addShapeLayer];
    [self startDisplayLink];
}

-(void)commitInit {
    self.waterWaveHeight = self.qmui_height / 3;
    self.speed = 0.02;
    self.zoomY = 1.0f;
    self.translateX = 0.0f;
    self.flag = NO;
}

- (void)addShapeLayer {
    self.shapeLayer = [CAShapeLayer layer];
    self.shapeLayer.path = [self waterWavePath];
    self.shapeLayer.fillColor = [_waveColor CGColor];
    self.shapeLayer.lineWidth = 0.1;
    self.shapeLayer.strokeColor = [_waveColor CGColor];
    [self.layer addSublayer:self.shapeLayer];
}

- (CGPathRef)waterWavePath {
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(0, self.waterWaveHeight)];
    
    CGFloat y = 0.0f;
    for (float x = 0; x <= self.qmui_width; x ++) {
        y = self.zoomY * sin( x / 180 * M_PI - 4 * self.translateX / M_PI ) * 5 + self.waterWaveHeight;
        [path addLineToPoint:CGPointMake(x, y)];
    }
    [path addLineToPoint:CGPointMake(self.qmui_width, self.qmui_height)];
    [path addLineToPoint:CGPointMake(0, self.qmui_height)];
    [path addLineToPoint:CGPointMake(0, self.waterWaveHeight)];
    [path closePath];
    
    return [path CGPath];
}

- (void)startDisplayLink {
    self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(handleDisplayLink:)];
    [self.displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
}

- (void)stopDisplayLink {
    [self.displayLink invalidate];
    self.displayLink = nil;
}

- (void)handleDisplayLink:(CADisplayLink *)displayLink {
    self.translateX += self.speed;// 平移
    if (!self.flag) {
        self.zoomY += 0.02;
        if (self.zoomY >= 1.5) {
            self.flag = YES;
        }
    } else {
        self.zoomY -= 0.02;
        if (self.zoomY <= 1.0) {
            self.flag = NO;
        }
    }
    self.shapeLayer.path = [self waterWavePath];
}
@end
